package com.universal_library.permission;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

/**
 * Created by solin on 2018/1/30.
 */

public class AcpService {
    private static final String TAG = "AcpService";
    /**
     * 检查权限 授权状态
     *
     * @param context
     * @param permission
     * @return
     */
    public int checkSelfPermission(Context context, String permission) {
        try {
            //获取pakcageInfo
            final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            //获取系统版本
            int targetSdkVersion = info.applicationInfo.targetSdkVersion;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //编译版本
                if (targetSdkVersion >= Build.VERSION_CODES.M) {
                    Log.i(TAG, "targetSdkVersion >= Build.VERSION_CODES.M");
                    return ContextCompat.checkSelfPermission(context, permission);
                } else {
                    return ContextCompat.checkSelfPermission(context, permission);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ContextCompat.checkSelfPermission(context, permission);
    }

    /**
     * 向系统请求权限  activity
     *
     * @param activity
     * @param permissions 权限的数组
     * @param requestCode 申请码
     */
    public void requestPermission(Activity activity, String[] permissions, int requestCode) {
        ActivityCompat.requestPermissions(activity, permissions, requestCode);
    }

    /**
     * 检查权限是否存在  拒绝后不在提示
     *
     * @param activity
     * @param permission
     * @return
     */
    public boolean shouldShowRequestPermissionRationale(Activity activity, String permission) {
        boolean shouldShowRational = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
        Log.i(TAG, "申请权限：" + shouldShowRational);
        return shouldShowRational;
    }
}
